/*
 * @Description: 字段匹配弹窗
 * @Author: Zzt
 * @Date: 2022-11-06 17:17:29
 * @LastEditTime: 2023-02-15 19:17:04
 */
import { jsonClone } from '@/utils';
import { Button, Select, Space, Table, Tabs } from 'antd';
import Column from 'antd/es/table/Column';
import { delItemById } from '@/utils/list';
import { v4 as uuidv4 } from 'uuid';
import { useEffect, useState } from 'react';
import { useMappingRelationContext } from '../../contexts/MappingRelationContext';
import { ILevel } from '@/interfaces/archiveType';
import { toInteger } from 'lodash-es';

const { TabPane } = Tabs;
const { Option } = Select;

class ExcelItem {
  key: string;
  sourceFieldName: string = null;
  sourceFieldType: number = null;

  relation: string = null;
  targetFieldName: string = null;
  targetFieldType: number = null;
  sortNo: number;
  constructor(idx: number) {
    this.sortNo = idx + 1;
    this.key = uuidv4();
  }
}
const relationship = [
  { id: 1, value: '等于' },
  { id: 2, value: '包含' },
  { id: 3, value: '属于' }
];
const FieldMatch = (props: any) => {
  const { updateTemplate, tplData, levelList } = props;
  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState<string>('');
  // 表格内容
  const [initTable, setInitTable] = useState([]);
  const { targetItems, fileList } = useMappingRelationContext();

  // excel列与元数据字段关系
  const [colRelation, setColRelation] = useState<any[]>([]);

  useEffect(() => {
    if (tplData?.length !== 0) {
      tplData.forEach((level: any) => {
        // levelList 增加key
        level.mapFieldList.forEach((item: any) => {
          item = {
            ...item,
            key: item.column + item.sourceFieldName
          };
        });
      });
      setColRelation(tplData);
    }
  }, [tplData]);

  useEffect(() => {
    if (levelList?.length > 0) {
      const highestLevel = levelList.find((level: ILevel) => level.levelNum === 1);
      setCurrentTab(`${highestLevel?.level}`);
    }
  }, [levelList]);

  useEffect(() => {
    setCurrentTab(`${levelList[0]?.level}`);
  }, [currentTab]);

  useEffect(() => {
    if (colRelation.length > 0) {
      setInitTable(colRelation.find((item) => `${item.level}` === currentTab).mapFieldList);
    }
  }, [currentTab]);
  /**
   * @description: tab切换
   * @param {string} key 选中的tab的key
   */
  const tabsChange = (key: string) => {
    saveTableForm();
    setCurrentTab(key);
  };

  useEffect(() => {
    if (initTable.length > 0) {
      saveTableForm();
    }
  }, [initTable]);
  /**
   * @description: 保存excel与元数据映射关系
   */
  const saveTableForm = () => {
    const newState = jsonClone(colRelation);
    if (newState.length > 0) {
      let flag: boolean = false;
      newState.forEach((item: any) => {
        if (item.level === parseInt(currentTab, 10)) {
          item.mapFieldList = initTable;
          flag = true;
        }
      });
      if (!flag) {
        newState.push({
          level: parseInt(currentTab, 10),
          mapFieldList: initTable
        });
      }
    } else {
      newState.push({
        level: parseInt(currentTab, 10),
        mapFieldList: initTable
      });
    }
    setColRelation(newState);
    updateTemplate(newState);
    return newState;
  };
  /**
   * @description: 清空全部数据
   */
  const clearAll = () => {
    const initData: any = {
      sourceFieldName: null,
      sourceFieldType: null,
      relation: null,
      targetFieldName: null,
      targetFieldType: null
    };
    setInitTable((state) => state.map((item) => ({ ...item, ...initData })));
  };
  const deleteItem = (key: string) => {
    setInitTable(delItemById(key, initTable, 'key'));
  };
  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    const newData = jsonClone(initTable);
    const index = newData.findIndex((item: any) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setInitTable(newData);
  };

  const operations = (
    <Space>
      <Button
        onClick={() => {
          setInitTable((state) => [...state, new ExcelItem(state.length)]);
        }}
      >
        添加一行
      </Button>
      <Button
        onClick={() => {
          clearAll();
        }}
      >
        清空内容
      </Button>
    </Space>
  );
  return (
    <>
      <Tabs activeKey={currentTab} onChange={tabsChange} tabBarExtraContent={operations}>
        {levelList.map((level: ILevel) => (
          <TabPane tab={level.levelName} key={level.level}>
            <Table dataSource={initTable} size="small" pagination={false} bordered>
              <Column
                title="序号"
                key="sortNo"
                align="center"
                render={(_val, _record, idx) => `${idx + 1}`}
              />
              <Column
                title={`源${level.levelName}字段`}
                dataIndex="sourceFieldName"
                key="sourceFieldName"
                align="center"
                render={(val, record: ILevel) => (
                  <Select
                    value={val}
                    style={{ width: 200 }}
                    placeholder="请选择字段"
                    size="small"
                    onChange={(value) => {
                      handleSave({
                        ...record,
                        sourceFieldName: value,
                        sourceFieldType: fileList.find((item: any) => item.field_name === value)
                          .field_type
                      });
                    }}
                  >
                    {fileList.map((item: any) => (
                      <Option key={item.field_name} value={item.field_name}>
                        {item.field_desc}
                      </Option>
                    ))}
                  </Select>
                )}
              />
              <Column
                title="关系"
                dataIndex="relation"
                key="relation"
                align="center"
                render={(val, record: any) => (
                  <Select
                    value={val * 1}
                    style={{ width: 140 }}
                    size="small"
                    placeholder="请选择字段"
                    onChange={(value) => {
                      handleSave({ ...record, relation: value });
                    }}
                  >
                    {relationship.map((item: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.value}
                      </Option>
                    ))}
                  </Select>
                )}
              />
              <Column
                title={`目标${level.levelName}字段`}
                dataIndex="targetFieldName"
                key="targetFieldName"
                align="center"
                render={(val, record: any) => (
                  <Select
                    value={val}
                    style={{ width: 140 }}
                    size="small"
                    placeholder="请选择字段"
                    onChange={(value) => {
                      handleSave({
                        ...record,
                        targetFieldName: value,
                        targetFieldType: targetItems.find((item: any) => item.field_name === value)
                          .field_type
                      });
                    }}
                  >
                    {targetItems.map((item: any) => (
                      <Option key={item.field_name} value={item.field_name}>
                        {item.field_desc}
                      </Option>
                    ))}
                  </Select>
                )}
              />
              <Column
                title="操作"
                dataIndex="action"
                key="action"
                align="center"
                render={(_val, record: any) => (
                  <Button
                    type="link"
                    size="small"
                    danger
                    onClick={() => {
                      deleteItem(record.key);
                    }}
                  >
                    删除
                  </Button>
                )}
              />
            </Table>
          </TabPane>
        ))}
      </Tabs>
    </>
  );
};
export default FieldMatch;
